var fun = require("./3_createStatement");
function statement(invoice, plays){
    return renderPlainText(fun.createStatementData(invoice, plays));
}

function renderPlainText(data) {
    let result = "Statement for " + data.customer + "\n";
    for (let perf of data.performance) {
        result += "-- " +  perf.play.name + ": " + usd(perf.amount) + " (" + perf.audience + " seats)" + "\n";
    };

    result += "Amount owed id " + usd(data.totalAmount) + "\n";
    result += "You earned " + data.totalVolumeCredits + " credits";
    console.log(result);
    return result;
}

function usd(aNumber){
    return new Intl.NumberFormat("en-US", {
        style: "currency", currency: "USD",
        minimumFractionDigits: 2
    }).format(aNumber/100);
}

/****************************************** */
function readJson(fileName, callback) {
    var fs = require('fs');
    fs.readFile(fileName, 'utf-8', (err, data) => {
        if (err) {
            console.error(err);
        } else {
            callback(JSON.parse(data));
        }
    });
}

var invoice;
var play;
readJson("invoices.json", (myData) => {
    invoice = myData;
});
readJson("play.json", (myData) => {
    play = myData;
});
var timer = setInterval(() => {
    if (invoice) {
        clearInterval(timer);
        statement(invoice, play);
    }
}, 500);